/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package trombinoscope.servlet;

import java.io.*;
import java.sql.SQLException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;
import trombinoscope.modele.*;

/**
 *
 * @author Jef
 */
public class MainController extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException{

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        try {
            String pageRedirection = "accueil.jsp";
            String action = request.getParameter("action");

            if (action.equals("authentification")) {
               pageRedirection = authentification(request,response);
               request.getRequestDispatcher(pageRedirection).forward(request, response);
            }


         //   if (action.equals("deconnexion")) {
         //       request.getSession().invalidate();
         //       pageRedirection = "authentification.jsp";
         //   }
        }
        catch (ServletException se){
            System.out.println("Erreur de Servlet");
            System.out.println (se.getMessage());
        }
        finally
        {
            out.close();
        }
    }

    private String authentification(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException
   {
        String pageRedirection="";
        String login = request.getParameter("email");
        String motDePasse = request.getParameter("motDePasse");

            if(UtilisateurDAO.isUserExistant(login, motDePasse))
            {
                Utilisateur userConnecte = UtilisateurDAO.getUserByMailPassword(login, motDePasse);

                String nom = userConnecte.getNom();
                String prenom = userConnecte.getPrenom();
                Integer idUtilisateur = userConnecte.getIdUser();
                boolean isAdmin = false;
                String statut;

                if(UtilisateurDAO.isAdmin(idUtilisateur))
                {
                    isAdmin=true;
                    statut = "admin";
                }
                else
                {
                    isAdmin=false;
                    statut = "etudiant";
                }

                // récupération de la liste des groupes
                ArrayList<Groupe> listeGroupe;
                listeGroupe = GroupeDAO.getListeGroupe();

                // récupèration du contexte de l'application
                ServletContext context = getServletContext();
                context.setAttribute("nomUser", nom);
                context.setAttribute("prenomUser", prenom);
                context.setAttribute("listegroupe", listeGroupe);
                context.setAttribute("isAdmin", isAdmin);

                // création d'un cookie pour le login
                Cookie loginCookie = new Cookie("login", login);
                response.addCookie(loginCookie);

                HttpSession session = request.getSession();
                session.setAttribute("nomUser", nom);
                session.setAttribute("prenomUser", prenom);

                pageRedirection = "accueil.jsp";
            }

            else
            {
                 pageRedirection = "authentification_echouee.jsp";
            }
          return pageRedirection;
        }






   /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
